package com.hyb.algorithm.data.struct.sort;

/**
 * @Author: huyanbing
 * @Date: 2021/9/13 7:51 下午
 */
public class QuickSort {


    public static void main(String[] args) {
        int[] nums=new int[]{10,9,8,7,6,5,4,3,2,1};
        sort(nums);

        for(int i=0;i<nums.length;i++){
            System.out.println(nums[i]+",");
        }

    }

    public static void sort(int[] arr) {
        quickSort(arr, 0, arr.length - 1);
    }


    /**
     * 递归使用快速排序，对arr[left...right]的范围进行排序
     *
     * @param arr
     * @param left
     * @param right
     */
    private static void quickSort(int[] arr, int left, int right) {

        if (left >= right) {
            return;
        }

        int partitionIndex = partition(arr, left, right);

        quickSort(arr, left, partitionIndex - 1);
        quickSort(arr, partitionIndex + 1, right);
    }


    /**
     * 对arr[left...right]部分进行partition操作
     * 返回partitionIndex 是 arr[left...partition-1]<arr[partitionIndex];
     * arr[partition+1....r]>arr[partitionIndex]
     *
     * @param arr
     * @param left
     * @param right
     * @return
     */
    private static int partition(int[] arr, int left, int right) {

        int v = arr[left];

        int partitionIndex = left;
        for (int i = left + 1; i <= right; i++) {
            if (arr[i] < v) {
                swap(arr, partitionIndex + 1, i);
                partitionIndex++;
            }
        }

        swap(arr, partitionIndex, left);

        return partitionIndex;
    }

    public static void swap(int[] nums,int src,int des){

        int temp=nums[src];
        nums[src]=nums[des];
        nums[des]=temp;
    }

}
